﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using YJKArchUtils.Utils;

namespace YJKRevitDimensionText.OneKeyPlanDim.DimData
{
	public class DbAxial
	{
		public XYZ AxialDir
		{
			get
			{
				return this.m_AxialDir;
			}
		}

		public DbAxial(Grid grid)
		{
			try
			{
				Line line = grid.Curve as Line;
				if (line != null)
				{
					this.m_lstGrid.Add(grid);
					this.m_AxialDir = line.Direction.Normalize();
				}
			}
			catch
			{
			}
		}

		public Grid GetGridNearestXZY(XYZ fixedXyz, ref double dMinDis)
		{
			Grid result = null;
			dMinDis = double.MaxValue;
			foreach (Grid grid in this.m_lstGrid)
			{
				Line line = grid.Curve as Line;
				if (!(line == null))
				{
					if (line.IsBound)
					{
						line.MakeUnbound();
					}
					double num = line.Distance(fixedXyz);
					if (Geometry.LessThan(num, dMinDis))
					{
						dMinDis = num;
						result = grid;
					}
				}
			}
			return result;
		}

		public Grid GetGridNearestXZY(XYZ fixedXyz, ref double dMinDis, ref XYZ ptOffset, XYZ vt)
		{
			Grid result = null;
			dMinDis = double.MaxValue;
			foreach (Grid grid in this.m_lstGrid)
			{
				Line line = grid.Curve as Line;
				if (!(line == null) && Geometry.IsVertical(line.Direction, vt, 1E-09))
				{
					if (line.IsBound)
					{
						line.MakeUnbound();
					}
					double num = line.Distance(fixedXyz);
					ptOffset = line.Project(fixedXyz).XYZPoint;
					if (Geometry.LessThan(num, dMinDis))
					{
						dMinDis = num;
						result = grid;
					}
				}
			}
			return result;
		}

		public bool IsSameDirection(Grid grid)
		{
			try
			{
				if ((grid.Curve as Line).Direction.Normalize().IsAlmostEqualTo(this.m_AxialDir.Normalize()))
				{
					this.m_lstGrid.Add(grid);
					return true;
				}
			}
			catch
			{
				return false;
			}
			return false;
		}

		private XYZ m_AxialDir = XYZ.BasisX;

		private List<Grid> m_lstGrid = new List<Grid>();
	}
}
